package com.yuanlang.web.controller.system;

import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.yuanlang.common.ResultMap;
import com.yuanlang.common.util.SystemConsts;
import com.yuanlang.common.util.SystemMsgCode;
import com.yuanlang.facade.model.system.*;
import com.yuanlang.services.system.TsMenuService;
import com.yuanlang.services.system.TsRoleMenuService;
import com.yuanlang.services.system.TsRoleService;
import com.yuanlang.web.controller.BaseController;
import javafx.scene.control.TreeView;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.*;

/**
 * company 重庆源狼软件科技有限责任公司
 * FileName TsMenuController
 * Package com.soft.link.controller.tsystem
 * Description 菜单显示层
 * author Administrator
 * create 2018-04-09 22:43
 * version V1.0
 */
@Controller
@RequestMapping("system/tsMenu")
public class TsMenuController extends BaseController {

    @Autowired(required = false)
    TsMenuService tsMenuService;

    @Autowired(required = false)
    TsRoleService tsRoleService;

    @Autowired(required = false)
    TsRoleMenuService tsRoleMenuService;

    /**
     * 分页查询菜单列表
     * @param tsMenu
     * @return
     */
    @RequestMapping("/findTsMenuPage")
    @ResponseBody
    public ResultMap findTsMenuPage(TsMenu tsMenu){
        try {
            ResultMap resultMap = new ResultMap();
            PageHelper.startPage(tsMenu.getPage(), tsMenu.getLimit());

            List<TsMenu> list = tsMenuService.findTsMenuPage(tsMenu);
            // 取分页信息
            PageInfo<TsMenu> pageInfo = new PageInfo<TsMenu>(list);
            resultMap.setCount(pageInfo.getTotal());
            resultMap.setData(list);
            return resultMap;
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }


    /**
     * 根据菜单ID查询菜单详情
     * @param menuId
     * @return
     */
    @RequestMapping("/findTsMenuById")
    @ResponseBody
    public ResultMap findTsMenuById(Long menuId){

        ResultMap resultMap = new ResultMap();
        try {
            TsMenuV tsMenu = tsMenuService.findTsMenuById(menuId);
            resultMap.setCode(SystemMsgCode.TS_MENU_QUERY_SUCCESS.getResultCode());
            resultMap.setMsg(SystemMsgCode.TS_MENU_QUERY_SUCCESS.getResultMessage());
            resultMap.setData(tsMenu);
        } catch (Exception e) {
            e.printStackTrace();
            resultMap.setCode(SystemMsgCode.TS_MENU_QUERY_FAILED.getResultCode());
            resultMap.setMsg(SystemMsgCode.TS_MENU_QUERY_FAILED.getResultMessage()+e.getLocalizedMessage());
        }

        return resultMap;
    }


    /**
     * 获取菜单树信息
     * @param
     * @return
     */
    @RequestMapping("/getMenuTree")
    @ResponseBody
    public List<TreeModel> getMenuTree(){
        try {
            TsUser tsUser = getTsUser();
            List<TsMenu> list = tsMenuService.findByOrders(tsUser);
            List<TreeModel> treeList = getChildNode(list);
            return treeList;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 登录后加载菜单树信息
     * @param
     * @return
     */
    @RequestMapping("/loadMenu")
    @ResponseBody
    public ResultMap loadMenu(){
        ResultMap resultMap = new ResultMap();
        try {

            TsUser tsUser = getTsUser();
            List<TsMenu> list = tsMenuService.findByOrders(tsUser);
            List<MenuModel> treeList = getChildMenu(list);
            resultMap.setCode(SystemMsgCode.TS_ROLE_OPER_SUCCESS.getResultCode());
            resultMap.setMsg(SystemMsgCode.TS_ROLE_OPER_SUCCESS.getResultMessage());
            resultMap.setData(treeList);

        } catch (Exception e) {
            e.printStackTrace();
            resultMap.setCode(SystemMsgCode.TS_ROLE_OPER_FAILED.getResultCode());
            resultMap.setMsg(SystemMsgCode.TS_ROLE_OPER_FAILED.getResultMessage() + e.getLocalizedMessage());
        }
        return resultMap;
    }

    /**
     * 新增菜单信息
     * @param tsMenu
     * @return
     */
    @RequestMapping("/saveTsMenu")
    @ResponseBody
    public ResultMap saveTsMenu(TsMenu tsMenu){
        ResultMap resultMap = checkNull(tsMenu);
        if(resultMap.getCode() != 0) return resultMap;
        try {
            // 新增
            TsUser tsUser = getTsUser();

            tsMenu.setCreateTime(Calendar.getInstance().getTime());
            tsMenu.setCreator(tsUser.getUserName());
            tsMenu.setCreatorId(tsUser.getUserId());

            tsMenu.setModifyerId(tsUser.getUserId());
            tsMenu.setModifyer(tsUser.getUserName());
            tsMenu.setModifyTime(Calendar.getInstance().getTime());

            tsMenu.setStatus(SystemConsts.SYS_STATUS_OPEN);
            Integer result = tsMenuService.saveOrUpdateTsMenu(tsMenu);
            if(result == 1){
                resultMap.setCode(SystemMsgCode.TS_MENU_OPER_SUCCESS.getResultCode());
                resultMap.setMsg(SystemMsgCode.TS_MENU_OPER_SUCCESS.getResultMessage());
            }else{
                resultMap.setCode(SystemMsgCode.TS_MENU_OPER_FAILED.getResultCode());
                resultMap.setMsg(SystemMsgCode.TS_MENU_OPER_FAILED.getResultMessage());
            }

        } catch (Exception e) {
            resultMap.setCode(SystemMsgCode.TS_MENU_OPER_FAILED.getResultCode());
            resultMap.setMsg(SystemMsgCode.TS_MENU_OPER_FAILED.getResultMessage() + e.getLocalizedMessage());
        }
        return resultMap;
    }


    /**
     * 修改菜单信息
     * @param tsMenu
     * @return
     */
    @RequestMapping("/updateTsMenu")
    @ResponseBody
    public ResultMap updateTsMenu(TsMenu tsMenu){
        ResultMap resultMap = checkNull(tsMenu);
        if(resultMap.getCode() != 0) return resultMap;
        try {
            TsUser tsUser = getTsUser();
            tsMenu.setModifyerId(tsUser.getUserId());
            tsMenu.setModifyer(tsUser.getUserName());
            tsMenu.setModifyTime(Calendar.getInstance().getTime());

            Integer result = tsMenuService.saveOrUpdateTsMenu(tsMenu);
            if(result == 1){
                resultMap.setCode(SystemMsgCode.TS_MENU_OPER_SUCCESS.getResultCode());
                resultMap.setMsg(SystemMsgCode.TS_MENU_OPER_SUCCESS.getResultMessage());
            }else{
                resultMap.setCode(SystemMsgCode.TS_MENU_OPER_FAILED.getResultCode());
                resultMap.setMsg(SystemMsgCode.TS_MENU_OPER_FAILED.getResultMessage());
            }

        } catch (Exception e) {
            resultMap.setCode(SystemMsgCode.TS_MENU_OPER_FAILED.getResultCode());
            resultMap.setMsg(SystemMsgCode.TS_MENU_OPER_FAILED.getResultMessage() + e.getLocalizedMessage());
        }
        return resultMap;
    }


    /**
     * 删除菜单
     * @param menuId
     * @return
     */
    @RequestMapping("delTsMenuById")
    @ResponseBody
    public ResultMap delTsMenuById(Long menuId){
        ResultMap resultMap = new ResultMap();
        try {
            // 根据菜单ID查询是否有角色在使用此菜单
            List<TsRoleMenu> roleMenuList = tsRoleMenuService.findTsRoleMenuListByMenuId(menuId);
            if(roleMenuList != null && roleMenuList.size() > 0){
                resultMap.setCode(SystemMsgCode.TS_MENU_HAS_BE_USED.getResultCode());
                resultMap.setMsg(SystemMsgCode.TS_MENU_HAS_BE_USED.getResultMessage());
            }else {
                TsMenu tsMenu = new TsMenu();
                tsMenu.setMenuId(menuId);
                tsMenu.setStatus(SystemConsts.SYS_STATUS_COLSE);
                tsMenuService.saveOrUpdateTsMenu(tsMenu);
                resultMap.setCode(SystemMsgCode.TS_MENU_OPER_SUCCESS.getResultCode());
                resultMap.setMsg(SystemMsgCode.TS_MENU_OPER_SUCCESS.getResultMessage());
            }
        } catch (Exception e) {
            e.printStackTrace();
            resultMap.setCode(SystemMsgCode.TS_MENU_OPER_FAILED.getResultCode());
            resultMap.setMsg(SystemMsgCode.TS_MENU_OPER_FAILED.getResultMessage()+e.getLocalizedMessage());
        }

        return resultMap;
    }



    /**
     * 菜单信息校验
     * @param tsMenu
     * @return
     */
    private ResultMap checkNull(TsMenu tsMenu){

        ResultMap resultMap = new ResultMap();
        resultMap.setCode(0);

        if(StringUtils.isEmpty(tsMenu.getMenuName())){
            resultMap.setCode(-1);
            resultMap.setMsg(SystemMsgCode.getSystemMsg(SystemMsgCode.TS_MENU_NAME_CAN_NOT_BE_NULL.getResultCode()));
            return resultMap;
        }
        if(StringUtils.isEmpty(tsMenu.getMenuCode())){
            resultMap.setCode(-1);
            resultMap.setMsg(SystemMsgCode.getSystemMsg(SystemMsgCode.TS_MENU_CODE_CAN_NOT_BE_NULL.getResultCode()));
            return resultMap;
        }
        if(tsMenu.getMenuCode() == null){
            resultMap.setCode(-1);
            resultMap.setMsg(SystemMsgCode.getSystemMsg(SystemMsgCode.TS_MENU_ORDER_CAN_NOT_BE_NULL.getResultCode()));
            return resultMap;
        }
        return resultMap;

    }

    /**
     * 集合转换为树形结构数据
     * @param list
     * @return
     */
    private List<TreeModel> getChildNode(List<TsMenu> list){

        List<TreeModel> resultList = new ArrayList<TreeModel>();
        if(list == null || list.size() == 0) return resultList;
        HashMap<Long, TreeModel> map = new HashMap<Long, TreeModel>();
        for (TsMenu tsMenu : list) {
            TreeModel treeModel = new TreeModel();
            treeModel.setId(tsMenu.getMenuId());
            treeModel.setName(tsMenu.getMenuName());
            treeModel.setChildren(new ArrayList<TreeModel>());
            map.put(tsMenu.getMenuId(), treeModel);
        }
        for (TsMenu tsMenu : list) {// 封装子节点到父节点
            if(map.containsKey(tsMenu.getParentMenuId())){
                map.get(tsMenu.getParentMenuId()).getChildren().add(map.get(tsMenu.getMenuId()));
                map.remove(tsMenu.getMenuId());
            }
        }

        for (Long key : map.keySet()) {
            resultList.add(map.get(key));
        }

        return resultList;
    }

    /**
     * 封装左侧菜单展示树
     * @param menuList
     * @return
     */
    private List<MenuModel> getChildMenu(List<TsMenu> menuList){
        List<MenuModel> resultList = new ArrayList<MenuModel>();
        if(menuList == null || menuList.size() == 0) return resultList;
        HashMap<Long, MenuModel> map = new HashMap<Long, MenuModel>();
        for (TsMenu tsMenu : menuList) {
            MenuModel menuModel = new MenuModel();
            menuModel.setMenuId(tsMenu.getMenuId());
            menuModel.setTitle(tsMenu.getMenuName());
            menuModel.setIcon(tsMenu.getMenuStyle());
            menuModel.setJump(tsMenu.getUrl());
            menuModel.setList(new ArrayList<MenuModel>());
            map.put(tsMenu.getMenuId(), menuModel);
        }
        for (TsMenu tsMenu : menuList) {// 封装子节点到父节点
            if(map.containsKey(tsMenu.getParentMenuId())){
                map.get(tsMenu.getParentMenuId()).getList().add(map.get(tsMenu.getMenuId()));
                map.remove(tsMenu.getMenuId());
            }
        }

        for (Long key : map.keySet()) {
            resultList.add(map.get(key));
        }

        return resultList;
    }


}
